#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main() {

    char delim = ',';

    string str = "1:10,2:12,3:10";  // 13

    istringstream ss( str );

    string                  token;
    vector< vector< int > > mmap;
    int                     allConsume = 0;

    while ( getline( ss, token, delim ) ) {
        vector< int > temp;
        size_t        pos      = token.find_first_of( ':' );
        int           uespower = stoi( token.substr( 0, pos ) );
        allConsume += uespower;
        int needMin = stoi( token.substr( pos + 1, token.size() - pos - 1 ) );
        temp.push_back( uespower );
        temp.push_back( needMin );
        mmap.push_back( temp );
    }

    // 贪心，剩的的越多越好，剩的越多，后边能处理的任务就越多
    sort( mmap.begin(), mmap.end(), []( vector< int >& a, vector< int >& b ) { return ( a[ 1 ] - a[ 0 ] ) > ( b[ 1 ] - b[ 0 ] ); } );

    int currentPower = 0;

    // 全局初始电量为队列第一个元素的初始电量，然后一个一个取，判断是 +=消耗电量 还是直接变成对应初始电量
    for ( int i = 0; i < mmap.size(); i++ ) {
        if ( currentPower < mmap[ i ][ 1 ] ) {
            currentPower = mmap[ i ][ 1 ];
        }
        currentPower -= mmap[ i ][ 0 ];
    }

    currentPower += allConsume;
    if ( currentPower > 4800 ) {
        cout << "-1";
    }
    else {
        cout << currentPower;
    }

    return 0;
}